package no.ntnu.fp.handlers;

import java.io.IOException;

import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.MeetingDeletedMessage;
import no.ntnu.fp.messages.impl.MeetingRejectedMessage;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.model.Notice.NoticeType;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.server.MainConnection;
import no.ntnu.fp.services.MeetingService;
import no.ntnu.fp.services.NoticeService;

public class MeetingRejectedHandler implements Handler {
	private final MeetingService meetingService;
	private final NoticeService noticeService;
	
	public MeetingRejectedHandler(MeetingService service, NoticeService nService){
		this.meetingService = service;
		this.noticeService = nService;
	}

	@Override
	public void handleMessage(Message message) {
		MeetingRejectedMessage m = (MeetingRejectedMessage)message;
		Meeting meeting = meetingService.markNotParticipating(m.getMeeting(), m.getEmployee());
		noticeService.notifyParticipants(meeting, 
				NoticeType.ParticipantDeclined, m.getEmployee());
		MeetingDeletedMessage reply = new MeetingDeletedMessage(meeting);
		Connection connection = MainConnection.getConnection(m.getEmployee());
		try {
			connection.send(reply.toString());
		} catch (IOException e) {
			throw new NetworkException("Could not send meeting deletion " +
					"acknowledgement for meeting " + m.getMeeting(), e);
		}
	}

}
